from database import db
from ..models.language import Language


class LanguageService(object):
    @classmethod
    def get_default(cls):
        return Language.query.filter(Language.type == Language.TYPE_DEFAULT).first()
    @classmethod
    def update(cls, id, data):

        type = data.get('type', 'normal')
        if type == Language.TYPE_DEFAULT:
            Language.query.update(
                {
                    'type': Language.TYPE_NORMAL
                }
            )
        Language.query.filter(Language.id == id) \
            .update(data)
        return Language.query.filter(Language.id == id) \
            .first()

    @classmethod
    def create(cls, **kwargs):

        type = kwargs.get('type', Language.TYPE_NORMAL)

        if type == Language.TYPE_DEFAULT:
            Language.query.update(
                {
                    'type': Language.TYPE_NORMAL
                }
            )

        language = Language(**kwargs)

        db.session.add(language)
        db.session.commit()
        return language

    @classmethod
    def remove(cls, obj):
        obj.id = '{}.REMOVED'.format(obj.id)
        obj.status = Language.STATUS_REMOVED
        obj.type = Language.TYPE_NORMAL
        db.session.commit()

    @classmethod
    def filter(cls, id=None, status=None, *args, **kwargs):
        query = Language.query

        if id:
            query = query.filter(Language.id == id)
        if status:
            query = query.filter(Language.status == status)
        else:
            query = query.filter(Language.status == Language.STATUS_ENABLED)

        return query.all()

    @classmethod
    def get_by_id(cls, id):
        return Language.query.filter(Language.id == id).first()
